/*
 * Copyright 2008 Jens Meiss
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package mtt.marks;

import java.util.Vector;

import javax.microedition.rms.RecordStore;

import mtt.marks.events.RefreshMarksModelDataEvent;
import mtt.marks.events.RefreshMarksViewEvent;
import mtt.rms.events.recordstores.marks.events.AddMarkRecordStoreListenerEvent;
import mtt.rms.events.recordstores.marks.events.GetVectorMarksEvent;
import mtt.rms.events.recordstores.marks.events.SetVectorMarksEvent;

import com.funambol.storage.ObjectStoreListener;

import hmvc.j2me.events.IEvent;
import hmvc.j2me.model.AModel;

/**
 * 
 * 
 * @author jens.meiss
 */
public class MarksModel extends AModel implements ObjectStoreListener {
	
	private boolean refreshModelData = true;

	private void getModelData() {
		
		if (refreshModelData) {
			getController().fireEventUp(
					new GetVectorMarksEvent(getController().getComponent()));
		}
		
	}

	public void handleEvent(IEvent event) {

		if (event instanceof SetVectorMarksEvent) {
			getController().fireEventLocal(
					new RefreshMarksViewEvent((Vector) event.getPayload()));
			refreshModelData = false;
		} else if (event instanceof RefreshMarksModelDataEvent) {
			getModelData();
		}
	}

	public void init() {
		getController().fireEventUp(new AddMarkRecordStoreListenerEvent(this));
		getModelData();
	}

	public void recordAdded(RecordStore recordStore, int recordId) {
		refreshModelData = true;
	}

	public void recordChanged(RecordStore recordStore, int recordId) {
		refreshModelData = true;
	}

	public void recordDeleted(RecordStore recordStore, int recordId) {
		refreshModelData = true;
	}

	public void registerEvents() {
		getController().register(SetVectorMarksEvent.class, this);
		getController().register(RefreshMarksModelDataEvent.class, this);
	}

	public void terminate() {
		// TODO Auto-generated method stub

	}

}
